<?php
namespace App\Http\Controllers\Api\Wx;

use Illuminate\Http\Request;

use App\Models\Customer\Customer;

use App\Models\Wx\WxCustomerCard;

use App\Models\Wx\WxCustomerCardMap;

use App\Http\Controllers\Controller;

use Illuminate\Support\Facades\Redis as Redis;

class WxCustomerCardController extends Controller
{

    /**
     * 检查微信会员卡领取
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function check(Request $request)
    {

        $session_id = $request->input('session_id', session_id());
        $platform = $request->input('platform', 6);

        if ( empty( $session_id ) ) {
            return response()->json([ 'code' => 100001 , 'message' => '缺少身份标识' ]);
        }

        $pcustID = get_customer_id($session_id, $platform);
        if ($pcustID) {
            return response()->json([ 'code' => 100002 , 'message' => '会员未登录' ]);
        }

        //查询用户是否已领取卡券
        $wx_customer_card_map = WxCustomerCardMap::select('cardId', 'cardCode', 'stat')->where('pcustID', $pcustID)->first();
        if (!$wx_customer_card_map || $wx_customer_card_map->stat == 2) {

            $card_data = WxCustomerCard::select('cardId')->where(['cardStatus' => 1])->first();

            if ( empty($card_data) ) {
                return response()->json([ 'code' => 100003 , 'message' => '会员卡信息不存在' ]);
            }

            $cust = Customer::select('cardNo')->find($pcustID);

            if ( empty($cust) ) {
                return response()->json([ 'code' => 100004 , 'message' => '会员卡号信息不存在' ]);
            }

            $ticket = redisTransformation(Redis::get('WXCARD_API_TICKET'));

            if ( !$ticket ) {
                $ticket  = $wechatMemberCardApi->getTicket('wx_card');
            }

            $card_id = $card_data->wechatCardId;
            $code = $cust->cardNo;
            $nonce_str = '6'; //  小程序渠道
            $timestamp = time();
            $card = array($ticket, $timestamp, $card_id, $code, $nonce_str);
            sort( $card, SORT_STRING ) ;
            $signature =  sha1( implode( $card ) );


            $return_data = [];


        } else {
            $return_data = [
                'receive' => 1,
                'cardId' => $wx_customer_card_map->cardId,
                'cardCode' => $wx_customer_card_map->cardCode,
            ];
        }

        return response()->json([ 'code' => 200 , 'message' => 'ok', 'data' => $return_data ]);

    }

}